package com.howinfun.netty.pool;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Howinfun
 * @desc 缓存客户端Channel，拿来做推送消息用
 * @date 2019/10/22
 */
@Slf4j
public class ClientChannelPool {
    /** 将channel缓存起来，key为IP:port  value为channel*/
    private static final Map<String, Channel> channels = new ConcurrentHashMap<>(100);

    public static Channel getChannel(String clientId){
        return channels.get(clientId);
    }
    public static Map<String, Channel> getChannels(){
        return channels;
    }
    /**
     * 添加客户端channel
     * @param clientId
     * @param channel
     */
    public static void addChannel(String clientId,Channel channel){
        if (!channels.containsKey(clientId)){
            channels.put(clientId,channel);
        }else{
            channels.remove(clientId);
            channels.put(clientId,channel);
        }
        log.info("Channel列表：数量->"+channels.size()+" 列表->"+channels.toString());
    }

    /**
     * 移除客户端channel
     * @param clientId
     */
    public static void removeChannel(String clientId){
        if (channels.containsKey(clientId)){
            channels.remove(clientId);
        }
        log.info("Channel列表：数量->"+channels.size()+" 列表->"+channels.toString());
    }
}
